﻿
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using GDFlacTool.Common;
using GDFlacTool.Properties;

namespace GDFlacTool.Forms
{
    public partial class FormRenameFolder : Form
    {
        private readonly Track _track;
        private MaskHelperCollection _masks;

        public FormRenameFolder(Track track)
        {
            InitializeComponent();

            _track = track;

            LoadMaskCombo();

            int index = cboMask.Items.IndexOf(MainSettings.Default.LastRenameFolderMask);

            if(index >= 0)
            {
                cboMask.SelectedIndex = index;
            }

            if(!string.IsNullOrEmpty(cboMask.Text))
            {
                _masks = new MaskHelperCollection { Mask = cboMask.Text };
            }
        }

        public string FolderName
        {
            get { return txtPreview.Text; }
        }

        private void LoadMaskCombo()
        {
            StringCollection masks = MaskEditorSettings.Default.SavedFolderRenameMasks;

            if (masks != null)
            {
                foreach (var mask in masks)
                {
                    cboMask.Items.Add(mask);
                }
            }
        }

        private void cboMask_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cboMask.Text))
            {
                _masks = new MaskHelperCollection { Mask = cboMask.Text };

                CreateNewFolderName();
            }
            else
            {
                txtPreview.Text = string.Empty;
            }
        }

        private void btnMaskEditorTagsFromFile_Click(object sender, EventArgs e)
        {
            var frm = new FormMaskEditor(cboMask.Text, "", RenameType.FOLDERRENAME, "");

            DialogResult result = frm.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                cboMask.Items.Clear();

                LoadMaskCombo();

                int index = cboMask.Items.IndexOf(frm.Mask);

                if (index >= 0)
                {
                    cboMask.SelectedIndex = index;
                }
                else
                {
                    cboMask.Text = frm.Mask;
                }

                if(!string.IsNullOrEmpty(cboMask.Text))
                {
                    _masks.Mask = frm.Mask;

                    CreateNewFolderName();
                }
                else
                {
                    txtPreview.Text = string.Empty;
                }
            }
        }  

        private void chkReplaceSpaces_CheckedChanged(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(txtPreview.Text))
            {
                if(chkReplaceSpaces.Checked)
                {
                    txtPreview.Text = txtPreview.Text.Replace(" ", "_");
                }
                else
                {
                    CreateNewFolderName();
                }
            }
        }

        private void ucCase_CheckedCaseTypeChanged(object sender, GDFlacTools.Controls.UCCase.CheckedCaseTypeChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPreview.Text))
            {
                if (e.IsActive)
                {
                    txtPreview.Text = CheckCase(txtPreview.Text, ucCase.GetCaseType());
                }
                else
                {
                    CreateNewFolderName();
                }
            }
        }

        private void CreateNewFolderName()
        {
            string newFolderName = _masks.Mask;

            foreach (MaskHelper mask in _masks)
            {
                if (newFolderName.Contains(mask.Mask))
                {
                    string replace = ReplaceStandardTags(mask.TagType);

                    if (replace != null)
                    {
                        newFolderName = newFolderName.Replace(mask.Mask, replace);
                    }
                }
            }

            if (string.IsNullOrEmpty(newFolderName))
            {
                return;
            }
            
            newFolderName = Functions.RemoveIllegalCharsFileName(newFolderName);

            if(chkReplaceSpaces.Checked)
            {
                newFolderName = newFolderName.Replace(" ", "_");
            }

            if(ucCase.CaseChecked)
            {
                newFolderName = CheckCase(newFolderName, ucCase.GetCaseType());
            }

            txtPreview.Text = newFolderName;
        }

        private string ReplaceStandardTags(MaskType type)
        {
            string result;

            if (type == MaskType.DISCNUMBER || type == MaskType.DISCNUMBERZERO)
            {
                string temp = _track.DiscNumber;

                if (temp == null)
                {
                    return string.Empty;
                }

                if (temp.Contains("/"))
                {
                    result = temp.Remove(temp.IndexOf("/", StringComparison.Ordinal));
                }
                else
                {
                    result = temp;
                }

                int number;

                if (int.TryParse(result, out number))
                {
                    result = string.Format("{0:0#}", number);
                }

                return result;
            }

            switch (type)
            {
                 case MaskType.ARTIST:
                    result = _track.Artist;
                    break;
                case MaskType.ALBUM:
                    result = _track.Album;
                    break;
                case MaskType.DATE:
                    result = _track.Year;
                    break;
                case MaskType.GENRE:
                    result = _track.Genre;
                    break;
                case MaskType.ALBUMARTIST:
                    result = _track.Albumartist;
                    break;
                case MaskType.BITRATE:
                    result = _track.BitRate.ToString(CultureInfo.InvariantCulture);
                    break;
                case MaskType.CONDUCTOR:
                    result = _track.Conductor;
                    break;
                case MaskType.COMPOSER:
                    result = _track.Composer;
                    break;
                case MaskType.EXTENSION:
                    result = Path.GetExtension(_track.FullPath);

                    if(!string.IsNullOrEmpty(result))
                    {
                        result = result.Replace(".", "");
                    }
                    break;
                default:
                    result = string.Empty;
                    break;
            }

            if (result == null)
            {
                result = string.Empty;
            }

            return result;
        }

        private string CheckCase(string text, CaseType type)
        {
            TextInfo myTI = new CultureInfo("en-US", false).TextInfo;

            string value = text;

            if (type != CaseType.None)
            {
                if (type == CaseType.Lower)
                {
                    value = myTI.ToLower(value);
                }

                if (type == CaseType.Upper)
                {
                    value = myTI.ToUpper(value);
                }

                if (type == CaseType.FirstLetter)
                {
                    value = myTI.ToTitleCase(value.ToLower());
                }

                if (type == CaseType.FirstWord)
                {
                    value = value.ToLower().ToUpperFirstLetter();
                }
            }

            return value;
        }

        private void FormRenameFolder_FormClosing(object sender, FormClosingEventArgs e)
        {
            MainSettings.Default.LastRenameFolderMask = cboMask.Text;
        }
    }
}
